const router = require('koa-router')()

const bcrypt = require("bcrypt")

const jwt = require("jsonwebtoken")

const {AdminUser, User} = require("../models/users")

const CtxBody = require("../models/config").CtxBody

const saltRounds = require("../models/config").saltRounds

const SecretKey = require("../models/config").SecretKey

const expiresIn = require("../models/config").expiresIn
router.prefix('/users')

// 后台管理员注册

router.post("/register", async ctx => {
  let { username, password, name } = ctx.request.body 
  if (username && password && name) {
    let user = await AdminUser.find({ username })
    // console.log(user);
    
    if (user.length) {
      CtxBody(ctx, 402, "")
    } else {
      let newUser = new AdminUser({
        username,
        password,
        name
      })
      let hash = await bcrypt.hash(newUser.password, saltRounds)
      newUser.password = hash
      let ret = await newUser.save()
      if (ret) {
        CtxBody(ctx, 202, "")
      } else {
        CtxBody(ctx, 302, "")
      }
    }
  } else {
    CtxBody(ctx, 30003, "")
  }
})

// 管理员 审核
router.post("/authorization", async ctx => {
  let { id } = ctx.request.body
  if (id) {
    let user = await AdminUser.findOneAndUpdate({ _id: id }, { $set: {
      status: "1"
    }})
    //console.log(user);
    if (user) {
      CtxBody(ctx, 204, "")
    } else {
      CtxBody(ctx, 304, "")
    }
  } else {
    CtxBody(ctx, 30003, "")
  }
})

// 后台封禁用户

router.post("/closeUser", async ctx => {
  let { id } = ctx.request.body
  if (id) {
    let user = await AdminUser.findOneAndUpdate({ _id: id }, { $set: {
      status: "2"
    }})
    //console.log(user);
    if (user) {
      CtxBody(ctx, 204, "")
    } else {
      CtxBody(ctx, 304, "")
    }
  } else {
    CtxBody(ctx, 30003, "")
  }
})


// 后台登录

router.post("/login", async ctx => {
  let { username, password } = ctx.request.body
  if (username && password) {
     let user = await AdminUser.findOne({ username, status: "1" })
     if (user) {
       let isRight = await bcrypt.compare(password, user.password)
       if (isRight) {
         let payLoad = {
           id: user._id,
           username: user.username
         }
         let token = await jwt.sign( payLoad, SecretKey, { expiresIn })
         CtxBody(ctx, 200, token)
       } else {
         CtxBody(ctx, 401, "")
       }
     } else {
       CtxBody(ctx, 404, "")
     }
  } else {
    CtxBody(ctx, 30003, "")
  }
})

// 获取用户信息

router.post("/getUserInfo", async ctx => {
  let token = ctx.request.header.authorization
  let payLoad = jwt.verify(token, SecretKey)
  if (payLoad) {
    let data = await AdminUser.findOne({ _id: payLoad.id })
    CtxBody(ctx, 200, data)
  } else {
    CtxBody(ctx, 404, "")
  }
})


// 小程序普通会员注册

router.post("/memberRegister", async ctx => {
  let { nickname, avatar, openid, userid } = ctx.request.body 
  if (userid) {
    console.log(1);
    
    let user = await User.findOne({ openid })
    if (user) {
      CtxBody(ctx, 402, "")
    } else {
      let newUser = new User({
        nickname, 
        avatar,
        openid 
      })
      let saveUser = await newUser.save()
      console.log(saveUser._id);
      
      let update = await User.findOneAndUpdate({ _id: saveUser._id}, {
        $set:{
          sub: userid
        }
      })
      let subupdate = await User.findOneAndUpdate({ _id: userid }, {
        $push: {
          children: saveUser._id
        }
      })
      CtxBody(ctx,204, "")
    } 
  } else {
    let user = await User.findOne({ openid })
    if (user) {
      CtxBody(ctx, 402, "")
    } else {
      let newUser = new User({
        nickname, 
        avatar,
        openid 
      })
      let saveUser = await newUser.save()
      CtxBody(ctx,204, "")
    } 
  }

 })

//  普通用户登录 openid  获取 token

router.post("/memberLogin", async ctx => {
  
  let { openid } = ctx.request.body 
  if (openid) {
    let user = await User.findOne({ openid })
    if (user) {
      let payLoad = {
        id: user._id,
        nickname: user.nickname
      }
      let token = await jwt.sign( payLoad, SecretKey, { expiresIn })
      CtxBody(ctx, 200, token)
    } else {
      CtxBody(ctx, 404, "")
    }
  } else {
    CtxBody(ctx, 30003, "")
  }
})

module.exports = router
